﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace fhs
{
    class VisionMgr
    {
        static readonly public Dictionary<VisionName.Vision, VisionBase> visions = new Dictionary<VisionName.Vision, VisionBase>();
        static readonly public Dictionary<VisionName.Vision, Form> visionForms = new Dictionary<VisionName.Vision, Form>();
        static readonly public Dictionary<VisionName.Vision, VisionBase.ParamBase> visionParams = new Dictionary<VisionName.Vision, VisionBase.ParamBase>();

        static public void Load()
        {
            foreach (var item in visionForms)
            {
                item.Value.Close();
            }
            visions.Clear();
            visionForms.Clear();
            visionParams.Clear();
            List<string> visionPaths = new List<string>();
            visionPaths.AddRange(Directory.GetDirectories(@".\VisionConfig\Common"));
            try
            {
                visionPaths.AddRange(Directory.GetDirectories($@".\VisionConfig\Product\{ProductMgr.currProduct}"));
            }
            catch (Exception)
            {
                LogMgr.Error($"{ProductMgr.currProduct} 视觉配置目录异常");
            }
            foreach (string visionPath in visionPaths)
            {
                string visionNameStr = Path.GetFileName(visionPath);
                VisionName.Vision visionName = (VisionName.Vision)(-1);
                if (StringToEnum.Convert(visionNameStr, ref visionName))
                {
                    VisionBase vision;
                    Form visionForm;
                    if (VisionInit.Init(visionName, out vision, out visionForm))
                    {
                        visionForm.TopLevel = false;
                        visionForm.Visible = false;
                        visions[visionName] = vision;
                        visionForms[visionName] = visionForm;
                        visionParams[visionName] = vision.LoadParam(ProductMgr.currProduct);
                    }
                    else
                    {
                        LogMgr.Error($"{visionNameStr} 视觉初始化失败");
                    }
                }
                else
                {
                    LogMgr.Error($"{visionNameStr} 视觉未定义");
                }
            }
        }

        static public void Save(VisionName.Vision visionName)
        {
            visionParams[visionName]?.Save(ProductMgr.currProduct);
        }

        static public void Save()
        {
            foreach (KeyValuePair<VisionName.Vision, VisionBase.ParamBase> visionItem in visionParams)
            {
                visionItem.Value?.Save(ProductMgr.currProduct);
            }
        }
    }
}
